﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using AutoUpdateLib;
using shop.Bll.trade;
using CommonTools.Controls;

namespace shop
{
    static class Program
    {
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);


        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            Application.ThreadException += Application_ThreadException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //ini文件保存到用户目录
#if DEBUG
            IniSet.SaveToUserDataDir("boya");
#else
            IniSet.SaveToUserDataDir("shop");
#endif



            Account ac = new Account(myApp.Owner);
            Application.Run(ac);
            if (ac.DialogResult == DialogResult.OK)
            {
                //初始化数据库
                if (shop.Model.DB.FSql == null)
                    DB.Init(myApp.Server, true);

                //如果登录前没有检查更新, 在这里检查
                CommonTools.CommonConfig.SqlConnString = DB.FSql.Ado.ConnectionString;

                if (myApp.AppUpdate(DB.FSql.Ado.ConnectionString))
                {
                    return;  //需要更新, 退出程序
                }


                CommonConfig.MainDock= myApp.MainDock = new MainDockForm { MenuWindow = new MenuForm(), Text = myApp.Owner.Title };
                Application.Run(myApp.MainDock);

            }

        }



        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }


        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            MessageBox.Show(string.Format("捕获到未处理异常：{0}\r\n异常信息：{1}\r\n异常堆栈：{2}\r\nCLR即将退出：{3}", ex.GetType(), ex.Message, ex.StackTrace, e.IsTerminating));
        }



        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            MessageBox.Show(string.Format("捕获到未处理异常：{0}\r\n异常信息：{1}\r\n异常堆栈：{2}", ex.GetType(), ex.Message, ex.StackTrace));
        }


    }
}
